/**
 * @file: index.
 * @intro: 数据请求统一封装.
 * @author: zzmhot.
 * @email: zzmhot@163.com.
 * @Date: 2017/5/8 14:52.
 * @Copyright(©) 2017 by zzmhot.
 *
 */

//导入模块
import axios from 'axios'
import {port_code, port_user} from '../../common/port_uri'
import router from 'src/router'
import {SET_USER_INFO} from 'store/actions/type'
import {server_base_url} from '../../common/config'
import {cookieStorage} from 'common/storage'
import * as prefix from '../../api/host'
import store from '../../store'
//设置用户信息action
export default function fetch(options) {
  return new Promise((resolve, reject) => {
    // https://github.com/mzabriskie/axios

    //创建一个axios实例
    const instance = axios.create({
      //设置默认根地址
      baseURL: server_base_url,
      //设置请求超时设置
      timeout: 5000,
      //设置请求时的header
      headers: {
        "x-auth-token": cookieStorage.get("token")
      }
    });

    instance.interceptors.response.use(function (response) {
      //如果是登录接口，则记录token
      if (options.url == prefix.prefix + port_user.login) {
        if (response.status == 200) {
          if (response.data.code == 200) {
            cookieStorage.set("token", response.headers['x-auth-token'], 'string');
          }
        }
      }
      return response;
    }, function (error) {
      // Do something with response error
      return Promise.reject(error);
    });


    //请求处理
    instance(options) // url - methods - data
      .then(({data: {code, message, data}}) => {
        //请求成功时,根据业务判断状态
        if (code === port_code.success) {
          if (data && data.total) {
            data.total = parseInt(data.total)
          }

          resolve({code, message, data})
        } else if (code === port_code.unLogin) { // 跳转登录界面
          store.state.user_info = null
          cookieStorage.remove('token')
          router.push({path: "/user/login"})
        } else {
          reject({code, message, data})
        }

      })
      .catch((error) => {
        //请求失败时,根据业务判断状态
      })
  })
}
